package org.mzy.system.controller;

import org.mzy.basic.anno.PreAuthorize;
import org.mzy.system.service.IRoleService;
import org.mzy.system.domain.Role;
import org.mzy.system.query.RoleQuery;
import org.mzy.basic.util.AjaxResult;
import org.mzy.basic.util.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/role")
public class RoleController {
    @Autowired
    public IRoleService roleService;


    /**
     * 保存和修改公用的
     *
     * @param role 传递的实体
     * @return Result转换结果
     */
    @PutMapping
    @PreAuthorize(name = "新增/修改角色", sn = "role:addOrUpdate")
    public AjaxResult addOrUpdate(@RequestBody Role role) {
        try {
            if (role.getId() != null)
                roleService.update(role);
            else
                roleService.add(role);
            return AjaxResult.me().success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().fail();
        }
    }

    /**
     * 删除对象信息
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "/{id}")
    @PreAuthorize(name = "删除角色", sn = "role:delete")
    public AjaxResult delete(@PathVariable("id") Long id) {
        try {
            roleService.delete(id);
            return AjaxResult.me().success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().fail();
        }
    }

    //获取用户
    @GetMapping("/{id}")
    @PreAuthorize(name = "根据id查询角色", sn = "role:get")
    public Role get(@PathVariable("id") Long id) {
        return roleService.findById(id);
    }


    /**
     * 查看所有的员工信息
     *
     * @return
     */
    @GetMapping()
    @PreAuthorize(name = "查询所有角色", sn = "role:list")
    public List<Role> list() {

        return roleService.findAll();
    }


    /**
     * 分页查询数据
     *
     * @param query 查询对象
     * @return PageList 分页对象
     */
    @PostMapping("/list")
    @PreAuthorize(name = "分页查询角色", sn = "role:json")
    public PageList<Role> json(@RequestBody RoleQuery query) {
        return roleService.queryByPage(query);
    }
}
